<template>
  <div class="upload-list">
    <Upload multiple type="drag" :accept="accept" :before-upload="beforeUpload">
      <div style="padding: 20px 0">
        <Icon type="ios-cloud-upload" size="28" style="color: #3399ff"></Icon>
        <p class="upload-label">点击或拖拽上传文件</p>
        <p class="upload-tip">支持 {{accept}}等格式<br>
          单文档最大限制100MB或1000页，单图片最大限制20MB<br>
          最多支持 ({{files.length}}/200) 个</p>
      </div>
    </Upload>

    <ul class="file-list">
      <li v-for="(item,index) in files" :key="index">
        <span>文件{{ item.name }}</span>

        <Icon type="md-close" size="16" @click="removeFile(index)" />
      </li>

    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Message } from 'view-ui-plus'
import { getFileExtension } from '@/util'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

// const accept = '.pdf, .doc, .docx, .txt, .md, .pptx, .ppt, .png, .jpg, .jpeg, .bmp, .gif, .xls, .xlsx'
const accept = '.pdf, .doc, .docx, .txt'

const files = ref([])

const beforeUpload = file => {
  if(files.value.length >= 200) {
    Message.warning('最多上传200个文件')
    return false
  }

  const wordType = getFileExtension(file.name)
  if (!accept.includes(wordType)) {
    Message.warning('暂不支持该格式文件上传')
    return false
  }

  const pictureMaxSize = 1024 * 1024 * 20
  const wordMaxSize = 1024 * 1024 * 100

  const isPicture = /^image\//.test(file.type)

  if(isPicture) {
    if(file.size > pictureMaxSize) {
      Message.warning('图片大小不能超过20MB')
      return false
    }
  }else{
    if(file.size > wordMaxSize) {
      Message.warning('文件大小不能超过100MB')
      return false
    }
  }

  files.value.push(file)
  emit('update:modelValue', files.value)
  return false
}

const removeFile = index => {
  files.value.splice(index,1)
}
</script>

<style scoped lang="scss">
.upload-list {
  width: 500px;
  .ivu-upload {
    :deep(.ivu-upload-list) {
      .ivu-icon {
        margin-top: 6px;
      }
    }
    .upload-label {
      font-weight: bold;
    }
    .upload-tip {
      font-size: 12px;
      line-height: 1.5;
      padding: 0 20px;
      color: #666;
    }
  }

  .file-list {
    max-height: 600px;
    overflow-y: auto;
    li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #ddd;
      padding: 0 8px;
      border-radius: 4px;
      &:nth-child(n+2) {
        margin-top: 8px;
      }
      .ivu-icon-md-close{
        cursor: pointer;
        &:hover{
          opacity: .9;
        }
      }
    }
  }
}
</style>